<template>
<el-dialog
    :modal="false"
    :close-on-click-modal="false"
    width="65%"
    :visible.sync="visible"
  >
  <el-button type="primary"  v-print ="'#add1'">打印</el-button>
  <br><br>
    <div ref="add1" id="add1">
    <div style="width:100%;height:20px">
      <div style="display: inline-block;margin-left:2%">管理单位：盖章</div>
      <div style="display: inline-block;margin-left:62%;">单位：元</div>
    </div>  
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      
      style="width:100%;">
      <el-table-column
        prop="personalCode"
        header-align="center"
        align="center"
        label="个人编码"
        width="130%">
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="姓名"
        width="90%">
      </el-table-column>
      <el-table-column
        prop="housingArea"
        header-align="center"
        align="center"
        label="年龄"
        width="75%">
      </el-table-column>
      <el-table-column
        prop="community"
        header-align="center"
        align="center"
        label="工作年限"
        width="100%">
      </el-table-column>
      <el-table-column
        prop="totalMonthlyPension"
        header-align="center"
        align="center"
        label="原退休金"
        width="100%">
      </el-table-column>
      <el-table-column
        prop="ext1"
        header-align="center"
        align="center"
        label="2022年增加养老金"
        width="140%">
      </el-table-column>
      <el-table-column
        prop="ext3"
        header-align="center"
        align="center"
        label="增加后退休金"
        width="105%">
      </el-table-column>
      <el-table-column
        prop="yuYue"
        header-align="center"
        align="center"
        label="补发月数"
        width="100%">
      </el-table-column>
      <el-table-column
        prop="ext2"
        header-align="center"
        align="center"
        label="补发金额"
        width="100%">
      </el-table-column>
      <el-table-column
        prop="ext4"
        header-align="center"
        align="center"
        label="实发金额"
        width="100%">
      </el-table-column>
    </el-table><br>
    <div style="width:100%;height:20px">
      <div style="display: inline-block;margin-left:2%">主管领导：</div>
      <div style="display: inline-block;margin-left:12%;">审核人：</div>
      <div style="display: inline-block;margin-left:12%;">制表人：</div>
      <div style="display: inline-block;margin-left:12%;">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total">
        </el-pagination>
      </div>
      <div style="display: inline-block;margin-left:12%;">{{this.result}}</div>
    </div>
    </div>
    <br><br>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
   </el-dialog>
</template>
<script>
import Excel11 from './excelmodelspb.vue'
import AddOrUpdate from './adjustmentbasis-add-or-update'
import docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import JSZipUtils from 'jszip-utils';
import print from 'vue-print-nb';
import { saveAs } from 'file-saver';
  export default {
    data () {
      return {
        show3: false,
        visible: false,
        countyList: [],
        streetList: [],
        dataForm: {
          personalCode: '',
          name: '',
          sex: '',
          birthDate: '',
          workTime: '',
          workersClassification: '',
          duties: '',
          retirementTime:'',
          retirementStatus:'',
          totalMonthlyPension:'',
          ext1:'',
          ext3:'',
          phone:'',
          address:'',
          death:'',
        },
        exportList:[],
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        addOrUpdateVisible1:false,
        progressFlag: false,
        progressPercent: 0,
      }
    },
    props: {
    //自增幅度
    step: {
        type: Number,
        default: 5,
    },
    //初始值
    initVal: {
        type: Number,
        default: 0,
    },
    //到一定进度停止
    stopVal: {
        type: Number,
        default: 95,
    },
    //进度条继续到成功
    isOk: {
        type: Boolean,
        default: false,
    },
    },
    watch: {
    //监听组件props变化决定是否继续加载
    isOk() {
        let progressPercent = this.progressPercent
        let step = this.step
        let timer = setInterval(() => {
            progressPercent = progressPercent + step
            // 加载到百分百完成
            if (progressPercent >= 100) {

                // 关闭定时器
                clearInterval(timer)
                // 加载完成关闭进度条
                this.progressFlag = false
                return
            }
        }, 500)
    },
    },
    components: {
      AddOrUpdate,
      Excel11
    },
    activated () {
      this.getDataList()
      //this.getName()
    },
    created(){
      this.dataSex('AREA')
    },
    computed: {
        result() {
          
          // 实例化日期类
          var time = new Date();
          // 获取完整的年份(4位)
          var year = time.getFullYear();
          // 获取月份(0-11,0代表1月)
          var month = time.getMonth() + 1;
          // 获取日期(1-31)
          var date = time.getDate();
          // // 获取小时
          // var h = time.getHours();
          // h = h < 10 ? '0' + h : h;
          // // 获取分钟
          // var m = time.getMinutes();
          // m = m < 10 ? '0' + m : m;
          // // 获取秒钟
          // var s = time.getSeconds();
          // s = s < 10 ? '0' + s : s;
          // //测试打印
          // console.log(year + "年" + month + "月" + date + "日 " + h + ":" + m + ":" + s);
          
          // 合并返回
          return(year + "年" + month + "月" + date + "日 " ) ;
        }

    },

    methods: {
      test(){
          this.dataListLoading = true
          this.visible = true;
          this.$http({
            url: this.$http.adornUrl('/jxxm/retiredemployees/listAddPension'),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataList = data.page.list
              this.totalPage = data.page.totalCount
              
            } else {
              this.dataList = []
              this.totalPage = 0
             
            }
            this.dataListLoading = false
          })
      },
      // 获取数据列表
      getDataList () {
        // alert(this.dataForm.name);
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/jxxm/retiredemployees/listAddPension'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 获取查询数据列表
      getSearchDataList () {
        // alert(this.dataForm.name);
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/jxxm/retiredemployees/searchListDeath'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 10,
            'deathTime1':this.dataForm.deathTime1 || "",
            'deathTime2':this.dataForm.deathTime2 || "",
            'logoutDate1':this.dataForm.logoutDate1 || "",
            'logoutDate2':this.dataForm.logoutDate2 || "",
            'county':this.dataForm.county,
            'street':this.dataForm.street

          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },

      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle () {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init()
        })
      },
      exportData(){
          this.$http({
          url: this.$http.adornUrl('/jxxm/retiredemployees/listAddPensionExcel'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {     
          if (data && data.code === 0) {
              this.exportList = data.list
              this.export2Excel()
          } else if (data && data.code === 40190) {
              this.$Message.info('数据太多无法导出，请联系客服！')
          }
        })  
      },
      export2Excel() {
          require.ensure([], () => {
          const Export2Excel2 = require('../../../../static/excel/Export2Excel.js');
          const tHeader = ['个人编码', '姓名', '性别', '出生年月', '参加工作时间','退休时间','职务','区县','街道、乡镇','移交时间段','移交时间','职工分类','原退休金','2022年增加养老金','增加后退休金','补发月数','补发金额','实发金额'];
          const filterVal = ['personalCode', 'name', 'sex', 'birthDate', 'workTime','retirementTime','duties','county','street','handoverPeriod','handoverTime','workersClassification','totalMonthlyPension','ext1','ext3','yuYue','ext2','ext4'];
          const list = this.exportList;
          const data = this.formatJson(filterVal, list);
          Export2Excel2.export_json_to_excel(tHeader, data, '病故人员信息');
         
        })
         
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      dataSex(type){
         this.$http({
            url: this.$http.adornUrl("/sys/dict/select/"+type),
            method: "get",
            params: this.$http.adornParams(),
            })
            .then(({ data }) => {      
                this.countyList = data && data.code === 0 ? data.list : [];  
            })
      },
      //地区联动专用
      dataArea(val,type){
     
         this.$http({
            url: this.$http.adornUrl("/sys/dict/select/"+type),
            method: "get",
            params: this.$http.adornParams(),
            })
            .then(({ data }) => {
                if (type == "AREA") {
                  this.countyList = data && data.code === 0 ? data.list : [];
                }
                this.$http({
                  url: this.$http.adornUrl("/sys/dict/secondary/"+val),
                  method: "get",
                  params: this.$http.adornParams(),
                  }).then(({ data }) => {                 
                      if (type == "AREA") {
                      this.dataForm.street = null;
                      this.streetList = data && data.code === 0 ? data.list : [];
                    }
                     
                  })
            })
      },
      downLoad(){
        //显示进度条
        this.progressFlag = true
        // 初始化后加载进度，加载到百分之多少由stopVal决定
        this.progressPercent = this.initVal
        let step = this.step
        //每500ms执行一次函数（进度条加step=5%）
        let timer = setInterval(() => {
            this.progressPercent = this.progressPercent + step
            // 父组件数据加载完前进度条最多到stopVal的这个百分值
            if (this.progressPercent >= this.stopVal) {
              
                //停止执行
                clearInterval(timer)
                
                return
            }
        }, 1000)
        //下面就调用接口，调用完成就this.progressPercent=100
        //这部分我写完会更新
        this.$http({
          url: this.$http.adornUrl('/jxxm/retiredemployees/listAddPensionExcel'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {     
          if (data && data.code === 0) {
              this.exportList = data.list
              this.export2Excel()
              this.progressPercent=100
              // 加载完成关闭进度条
                this.progressFlag = false
          } else if (data && data.code === 40190) {
              this.$Message.info('数据太多无法导出，请联系客服！')
          }
        })  
    },
    isOver(){
      
       this.$confirm(`确定进行【调资结束】操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          distinguishCancelAndClose: true,   
          closeOnClickModal: false
        }).then(() => { 
            this.dataListLoading = true
             this.$http({
              url: this.$http.adornUrl('/jxxm/retiredemployees/isOver'),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {     
              if (data && data.code === 0) {
                  this.$message({
                  message: '操作成功',
                  type: 'success'
              })
              } else{
                  this.$message.error('调资失败！')
              }
              this.dataListLoading = false
            })
         })      
      },
      
      downloadSpb(id) {

            this.$http({
              url: this.$http.adornUrl(`/jxxm/adjustmentbasis/infoList`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                var datas = data.adjustmentBasis.tzgj;
               
                  this.$http({
                    url: this.$http.adornUrl(
                      `/jxxm/retiredemployees/pension/${id}`
                    ),
                    method: "get",
                    params: this.$http.adornParams(),
                  }).then(({ data }) => {
                    if (data && data.code === 0) {
                      var data = { 
                        personalCode: data.retiredEmployees.personalCode,
                        name: data.retiredEmployees.name,
                        sex: data.retiredEmployees.sex,
                        birthDate: data.retiredEmployees.birthDate,
                        workTime: data.retiredEmployees.workTime,
                        wcc: data.retiredEmployees.workersClassification,
                        duties: data.retiredEmployees.duties,
                        txsj: data.retiredEmployees.retirementTime,
                        rms: data.retiredEmployees.retirementStatus,
                        tmp: data.retiredEmployees.totalMonthlyPension,
                        ext1:data.retiredEmployees.ext1,
                        ext3:data.retiredEmployees.ext3,
                        dwyj:datas,
                        qhjd:data.retiredEmployees.phone,
                        dq:data.retiredEmployees.address,
                        dqsj:data.retiredEmployees.death,
                      }
                      exportDocx(window.SITE_CONFIG.cdnUrl + "/static/assets/spb.docx", data, `调资审批表.docx`);  
                    }
                  });
              }
            }) 

             
		   },
        test11 (id) {
       
          this.addOrUpdateVisible1 = true
          this.$nextTick(() => {
            this.$refs.Excel11.test(id)
          })
       
        
      },
    }
  }
  export const exportDocx = (tempDocxPath, data, fileName) => {
  // 读取并获得模板文件的二进制内容
  JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
    if (error) {
      throw error;
    }
    let zip = new PizZip(content);
    let doc = new docxtemplater().loadZip(zip);
    doc.setData(data);
    try {
      // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
      doc.render();
    } catch (error) {
      let e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties,
      };
      console.log({
        error: e
      });
      // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
      throw error;
    }
    let out = doc.getZip().generate({
      type: "blob",
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    }); //Output the document using Data-URI
    saveAs(out, fileName);
    // var newPreview = document.getElementById("file");
    // const docx = require('docx-preview');
    // window.JSZip = require('jszip')
    // docx.renderAsync(out,newPreview) 
   

  });
};
</script>
